package com.gd.iot.energy.filter;

import cn.hutool.core.util.StrUtil;
import cn.hutool.http.ContentType;
import cn.hutool.json.JSONUtil;
import com.gd.iot.energy.code.ResponseCode;
import com.gd.iot.energy.consts.SystemConsts;
import com.gd.iot.energy.entity.ResponseEntity;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.web.filter.authc.FormAuthenticationFilter;
import org.apache.shiro.web.util.WebUtils;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletResponse;

/**
 * 自定义过滤器，ajax请求数据 以json格式返回
 */
@Slf4j
public class SimpleFormAuthenticationFilter extends FormAuthenticationFilter {


    @Override
    protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws Exception {
        if (isLoginRequest(request, response)) {
            if (isLoginSubmission(request, response)) {
                if (log.isTraceEnabled()) {
                    log.trace("Login submission detected.  Attempting to execute login.");
                }
                return executeLogin(request, response);
            } else {
                if (log.isTraceEnabled()) {
                    log.trace("Login page view.");
                }
                return true;
            }
        } else {
            HttpServletResponse httpServletResponse = WebUtils.toHttp(response);
            httpServletResponse.setContentType(ContentType.JSON.getValue());
            httpServletResponse.setCharacterEncoding("UTF-8");
            String token = WebUtils.toHttp(request).getHeader(SystemConsts.TOKEN_KEY);
            String msg = StrUtil.isBlank(token) ? "请登录后访问" : "登录信息已过期，请重新登录";
            httpServletResponse.getWriter()
                    .write(JSONUtil.toJsonStr(new ResponseEntity<>(ResponseCode.AUTH_FAILED, msg)));
            return false;
        }
    }

}